import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import CONFIG from '@/config'
import Home from '@/view/home'
// 移动端中文网站路由
const Invitation = resolve => require(['@/view/invitation/index'], resolve)
const Invitefriends = resolve => require(['@/view/invitation/inviteFriends'], resolve)
const Notice = resolve => require(['@/view/notice'], resolve)
const Details = resolve => require(['@/view/details'], resolve)
Vue.use(Router)
const router = new Router({
  // base: '/app/',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {'title': '主页'}
    },
    {
      path: '/invitefriends',
      name: 'Invitefriends',
      component: Invitefriends,
      meta: {'title': '邀请好友'}
    },
    {
      path: '/notice',
      name: 'Notice',
      component: Notice,
      meta: {'title': '公告'}
    },
    {
      path: '/details',
      name: 'Details',
      component: Details,
      meta: {'title': '公告'}
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    }
  }
})
router.beforeEach((to, from, next) => {
  goPAGE(to)
  if (store.state && !to.matched.some(v => v.meta.disableLoading)) { // 路由跳转，显示菊花~ Author by Dio Zhu. on 2017.2.17
    store.commit('app_openLoading')
  }

  function setSlide(slide) {
    store.commit('app_setSlideName', slide)
  }

  if (to.query.key) {
    if (parseInt(from.query.key) > parseInt(to.query.key)) {
      setSlide('left')
    } else {
      setSlide('right')
    }
  } else {
    if (from.name) {
      setSlide('left')
    } else {
      setSlide('right')
    }
  }
  next()
})
router.afterEach(route => {
  if (route.meta && route.meta.title) {
    document.title = route.meta.title
  } else {
    document.title = CONFIG.TITLE
  }
  try { // 隐藏loading
    if (store && store.state) {
      setTimeout(function () {
        store.commit('app_closeLoading')
      }, 400)
    }
  } catch (e) {
    console.error('router.afterEach: ', e)
  }
})
let p = router.push
let r = router.replace
router.push = function (params) {
  if (params.query) {
    params.query.key = Date.now()
  } else {
    params.query = {key: Date.now()}
  }
  p.call(router, params)
}
router.replace = function (params) {
  if (params.query) {
    params.query.key = Date.now()
  } else {
    params.query = {key: Date.now()}
  }
  r.call(router, params)
}

function goPAGE(route) {
  if (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
      window.location.href = 'http://trongame.fun/#' + route.fullPath
  }
}

// 导出router对象
export default router
